import { get as getVal } from "svelte/store";
import { canUse, isEmpty } from "@util/checker";
import { createUser, authUser, sendCode, signInUser } from "@api/user";
import { MOCK_ID_KEY, SIGN_IN_FLAG_KEY, mockId$, signInFlag$, user$ } from "@store/entity/User";
import { browser } from "$app/environment";
// import { loadingApps } from "./app";

export const anonymousAuth = async (cb?: () => any) => {
  mockId$.subscribe(async (v) => {
    if (canUse(v) && !isEmpty(v)) {
      const user = await authUser(v);
      user$.set(user);
      let $signInFlag$ = getVal(signInFlag$);
      if ($signInFlag$) {
        console.log("signIn success!");
      } else {
        console.log("anonymousAuth success!");
      }
    } else {
      const user = await createUser();
      browser && localStorage.setItem(MOCK_ID_KEY, user.mock_id);
      mockId$.set(user.mock_id);
      user$.set(user);
    }

    cb && (await cb());
  })();
};

export const sendCodeAtSignIn = async (mobile: string) => {
  await sendCode(mobile);
};

export const signIn = async (mobile: string, code: string) => {
  let $anonymousUser$ = getVal(user$);
  const user = await signInUser($anonymousUser$, mobile, code);
  let refreshData = false
  if ($anonymousUser$.mock_id !==  user.mock_id) {
    browser && localStorage.setItem(MOCK_ID_KEY, user.mock_id);
    mockId$.set(user.mock_id);
    refreshData = true
  }
  user$.set(user);
  browser && localStorage.setItem(SIGN_IN_FLAG_KEY, "true");
  signInFlag$.set(true)
  
  if (refreshData) {
    // await loadingApps()
  }
};

export const signOut = async () => {
  browser && localStorage.removeItem(SIGN_IN_FLAG_KEY);
  signInFlag$.set(false)
}